"use strict";
const tool = require("../utils/tool");
const Constants = require("../config");
const _ = require("lodash");
const request = require("request-promise-native");
const moment = require("moment");
const mongoose = require("mongoose");
const receiptModel = mongoose.model("receipt");
const envelopModel = mongoose.model("envelop");

const apiBase = {
  "status":0,
  "message":"everything is ok"
}

async function getCardByUsername(req, res) {
  const client = tool.getResponseFunc(res);
  let result = {};
  try {
    const type = req.query.type;
    const username = req.query.username;
    const userId = req.query.userid;
    console.log(`type:${type}`);
    console.log(`username:${username}`);
    console.log(`userId:${userId}`);
    // if(!username){
    //   console.log('未找到username');
    //   res.json({
    //     ...apiBase,
    //     result: {
    //       items: []
    //     }
    //   });
    //   return;
    // }
    const cards = Constants.cards;
    if(cards[type] && cards[type].type == "fanwei"){
      const fanweiServerConfig = cards[type];
      // dduserid=100040
      const fanweiUsername = await getFanweiUsername(username);
      // const fanweiUsername = 1453;
      console.log(`fanweiUsername:${fanweiUsername}`);
      if(!fanweiUsername){
        if(req.query.resData){
          return {
            status: 400
          };
        }
        res.json({
          ...apiBase,
          result: {
            items: []
          }
        });
        return;
      }
      const params = {
        method: "GET",
        url: `${fanweiServerConfig.url}&userid=${fanweiUsername}`,
        json: true,
      }
      console.log(`请求泛微服务：${params.url}`);
      const fanweiResult = await request(params);
      // console.log(fanweiResult);
      if(!fanweiResult || !fanweiResult.list)throw new Error('泛微模块数据出错');
      switch (type) {
        case 'gonggao':
          result = transGonggaoData(fanweiResult.list, fanweiServerConfig, fanweiUsername);
          break;
        case 'daiban':
          result = transDaibanData(fanweiResult.list, fanweiServerConfig, fanweiUsername);
          break;
        case 'tongzhi':
          result = transTongzhiData(fanweiResult.list, fanweiServerConfig, fanweiUsername);
          break;
      }
    }else if (cards[type] && cards[type].type == "service"){
      // meessageType:
      // ACK,
      // ARTICLE,
      // CMD,
      // CUSTOM,
      // TEXT,
      // IMAGE,
      // VOICE,
      // VIDEO,
      // FILE,
      // MULTIPART,
      // LOC,
      // EVENT,
      // NOTICE,
      // SHARE,
      // VOIP,
      // BURN_TEXT,
      // BURN_IMAGE,
      // BURN_VOICE,
      // TEMPLATE,
      // BING_TEXT,
      // BING_VOICE,
      // RED_ENVELOP,
      // STICKER;
      switch (type) {
        case 'xinwen':
          result = await transXinwenData(cards[type].serviceId, userId, 'ARTICLE');
          break;
        case 'tongzhi2':
          result = await transDaibanData(fanweiResult.list, fanweiServerConfig, fanweiUsername);
          break;
      }
    }else{
      throw new Error('未找到对应card');
    }
    console.log(result);
    if(req.query.resData)return result;
    res.json(result);
  } catch (e) {
    client.fail(e);
  }
}

async function transXinwenData(serviceId, userId, messageType){
  try {
    // lean 转换bson；limit 100条消息， 100消息也没有5条图文就算了；
    let results = [];
    const evpIdsDocs = await receiptModel.find({"addresserId": serviceId, "recipientId": userId, "evpType": messageType}).sort({evpTime: -1}).limit(15).lean();
    const evpIds = _.map(evpIdsDocs, 'evpId');
    const filterEvpOfService = await envelopModel.find({"undo": false, "removed": false, "deliveryId": {$in: evpIds}, bodyType: messageType}).lean();
    console.log(`serveiceMessage:${filterEvpOfService}`);
    if(messageType == 'ARTICLE'){
      _.forEach(filterEvpOfService, item => {
        const messageBodyBase64 = new Buffer(item.body, 'base64')
        const messageBody = JSON.parse(messageBodyBase64.toString());//消息体
        _.forEach(messageBody.articles, article => {
          results.push({
            "title": article.title,
            "sub_title":"",
            "date_time": moment(item.deliveryTime).format('YYYY-MM-DD HH:mm'), //来源
            "source":"", //事件类型
            "event_type":"Url", //事件值
            "event_value": article.url,
            "icon_value": `${article.cover_media_id}`,
            "icon_type": 'mediaId'
          })
        })
      })
    }
    results = _.sortBy(results, function(item){
      return -moment(item.date_time).valueOf();
    })
    return {
      ...apiBase,
      result: {
        items: results
      }
    }
  } catch (e) {
    console.log(e);
  }
}

const transTongzhiData = (list, fanweiServerConfig, fanweiUsername) => {
  const newList = _.map(list, item => {
      return {
        //标题
         "title": item.wftitle,
         //时间
         "date_time": item.createtime,
         //来源
         "source": "",
         //事件类型
         "event_type":"url",
         //事件值
         "event_value":`${fanweiServerConfig.detailUrl}detailid=${item.requestid}&code=${fanweiUsername}`
     }
  });
  return {
    ...apiBase,
    result: {
      items: newList
    }
  }
}

const transGonggaoData = (list, fanweiServerConfig, fanweiUsername) => {
  const newList = _.map(list, item => {
      return {
        //标题
         "title": item.docsubject,
         //时间
         "date_time": item.doccreatedate,
         //来源
         "source": item.departmentname,
         //事件类型
         "event_type":"url",
         //事件值
         "event_value":`${fanweiServerConfig.detailUrl}detailid=${item.docid}&code=${fanweiUsername}`
     }
  });
  return {
    ...apiBase,
    result: {
      items: newList
    }
  }
}

const transDaibanData = (list, fanweiServerConfig, fanweiUsername) => {
  const newList = _.map(list, item => {
      return {
        //标题
         "title": item.wftitle,
         //时间
         "date_time": item.createtime,
         //来源
         "source": "",
         //事件类型
         "event_type":"url",
         //事件值
         "event_value": `${fanweiServerConfig.detailUrl}detailid=${item.requestid}&code=${fanweiUsername}`
     }
  });
  return {
    ...apiBase,
    result: {
      items: newList
    }
  }
}

async function getFanweiUsername(workplusUsername){
  try{
    const params = {
      method: "GET",
      url: `${Constants.transUsernameUrl}&dduserid=${workplusUsername}`,
      json: true,
    }
    const result = await request(params);
    if(result.status == 0 && result.ddUserInfo[0].outuserid){
      return result.ddUserInfo[0].outuserid;
    }else{
      throw new Error('泛微转换username失败')
    }
  }catch(e){
    console.log(e);
  }
}

module.exports = {
  getCardByUsername
}
